package com.handu.luna.boss.controller;

import com.handu.luna.core.domain.goods.Goods;
import com.handu.luna.core.domain.promotion.Promotion.PromotionStatus;
import com.handu.luna.core.domain.promotion.combo.Combo;
import com.handu.luna.core.domain.search.ComboSearch;
import com.handu.luna.core.domain.search.GoodsSearchCondition;

import net.sf.json.JSONObject;

import org.apache.commons.lang.StringUtils;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.web.PageableDefault;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.validation.Valid;

import java.io.UnsupportedEncodingException;
import java.util.Base64;

/**
 * Created by zhq on 2014/7/23.
 */
@Controller
@RequestMapping("/promotion/combo/*")
public class ComboController extends BaseController {

    @RequestMapping(method = RequestMethod.GET)
    public BossModel index(String viewState,
                           @PageableDefault(page = 0,size = DEFAULT_PAGE_SIZE,sort = {"createdDate"},direction = Sort.Direction.DESC) Pageable pageable)
            throws UnsupportedEncodingException{
        ComboSearch search;
        if (viewState != null && !viewState.trim().equals("") && !viewState.equals("-1")) {
            //解析传递过来的查询json字符串
            search = (ComboSearch) JSONObject.toBean(JSONObject.fromObject(new String(Base64.getUrlDecoder().decode(viewState), "UTF-8")), ComboSearch.class);
            return createModel()
                    .add("combos", context.getComboRepository().findAll(Combo.complexQuery(search), pageable))
                    .add("viewState", viewState)
                    .add("comboSearch", search)
                    .add("statusList", PromotionStatus.values());
        } else {
            search = new ComboSearch();
            return createModel()
                    .add("combos", context.getComboRepository().findAll(pageable))
                    .add("comboSearch", search)
                    .add("viewState", "")
                    .add("statusList", PromotionStatus.values());
        }
    }
    @RequestMapping(method = RequestMethod.POST)
    public BossModel index(ComboSearch comboSearch ,
                           @PageableDefault(page = 0,size = DEFAULT_PAGE_SIZE,sort = {"createdDate"},direction = Sort.Direction.DESC) Pageable pageable)
            throws UnsupportedEncodingException {
        String viewState;
        if (StringUtils.isNotBlank(comboSearch.getComboName()) ||
                StringUtils.isNotBlank(comboSearch.getComboStartDate()) ||
                StringUtils.isNotBlank(comboSearch.getComboEndDate()) ||
                StringUtils.isNotBlank(comboSearch.getStatus())) {
            viewState = Base64.getUrlEncoder().encodeToString(JSONObject.fromObject(comboSearch).toString().getBytes("UTF-8"));
        } else {
            viewState = "";
        }
        return createModel()
                .add("combos", context.getComboRepository().findAll(Combo.complexQuery(comboSearch), pageable))
                .add("comboSearch", comboSearch)
                .add("viewState", viewState)
                .add("statusList", PromotionStatus.values());
    }

    @RequestMapping(value = "add")
    public BossModel add(int page , String viewState){
        GoodsSearchCondition searchCondition = new GoodsSearchCondition(GoodsSearchCondition.SearchType.COMBO);
        return createModel("promotion/combo/save")
                .add("combo", new Combo())
                .add("searchCondition",searchCondition)
                .add("selectableGoods", context.getGoodsRepository().findAll(searchCondition.searchabledGoods(searchCondition)))
                .add("brands", context.getBrandRepository().findAll())
                .add("categorys", context.getCategoryRepository().findAll())
                .add("page",page)
                .add("viewState",(viewState==null?"":viewState));
    }

    @RequestMapping(value = "view/{id}")
    public BossModel view(@PathVariable long id,int page,String viewState){
        return createModel("promotion/combo/info")
                .add("combo",context.getComboRepository().findOne(id))
                .add("page",page)
                .add("viewState",viewState);
    }

    @RequestMapping(value = "edit/{id}")
    public BossModel edit(@PathVariable long id,int page,String viewState){
        GoodsSearchCondition searchCondition = new GoodsSearchCondition(id,GoodsSearchCondition.SearchType.COMBO);
        return createModel("promotion/combo/save")
                .add("searchCondition",searchCondition)
                .add("combo",context.getComboRepository().findOne(id))
                .add("selectableGoods", context.getGoodsRepository().findAll(searchCondition.searchabledGoods(searchCondition)))
                .add("brands", context.getBrandRepository().findAll())
                .add("categorys", context.getCategoryRepository().findAll())
                .add("page",page)
                .add("viewState",viewState);
    }

    @RequestMapping(value = "delete",method = RequestMethod.POST)
    public BossModel delete(long id,
                            @PageableDefault(page = 0,size = DEFAULT_PAGE_SIZE) Pageable pageable,
                            String viewState) throws UnsupportedEncodingException{
        context.getComboRepository().delete(id);
        if (viewState != null && !viewState.trim().equals("") && !viewState.equals("-1")) {
            //解析传递过来的查询json字符串
            ComboSearch search = (ComboSearch) JSONObject.toBean(JSONObject.fromObject(new String(Base64.getUrlDecoder().decode(viewState), "UTF-8")), ComboSearch.class);
            return createModel("promotion/combo/combo_table")
                    .add("combos", context.getComboRepository().findAll(Combo.complexQuery(search), pageable))
                    .add("viewState", viewState);
        } else {
            return createModel("promotion/combo/combo_table")
                    .add("combos", context.getComboRepository().findAll(pageable))
                    .add("viewState", "");
        }
    }

    @RequestMapping(value = "save",method = RequestMethod.POST)
    @InitBinder(value = {"name","startDate","endDate","displayOrder","price","description","comboGoodsIds"})
    public BossModel save(@Valid Combo combo,final BindingResult bindingResult,RedirectAttributes redirectAttributes,int page,String viewState){
        if (bindingResult.hasErrors()) {
            return createModel("promotion/combo/save")
                    .add("combo",combo)
                    .add("selectableGoods", context.getGoodsRepository().findAll(new Goods().searchSelectAble(Goods.SearchType.COMBOSEARCH, 0, null, null, null, null)))
                    .add("brands", context.getBrandRepository().findAll())
                    .add("categorys", context.getCategoryRepository().findAll());
        }
        String message = "";
        if(null==combo.getId() || combo.getId() == 0){
            message = "添加套餐"+combo.getName()+ "成功";
        }else{
            message = "修改套餐"+combo.getName()+ "成功";
        }
        if (!(combo.getId()==null||combo.getId()==0)){
            redirectAttributes.addAttribute("page",page);
            redirectAttributes.addAttribute("viewState",StringUtils.isNotBlank(viewState)?viewState:"");
        }
        context.getComboRepository().save(combo);
        redirectAttributes.addFlashAttribute("message", message);
        return createModel("redirect:index");
    }

}
